﻿using HtmlAgilityPack;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Cineman.ViewModels
{
    public class ViewModel
    {
        public MovieGroup Movies { get; set; }
        public MovieGroup Today { get; set; }
        public MovieGroup ComingSoon { get; set; }
        public bool IsDataLoaded { get; set; }
        public bool IsServerReachable { get; set; }
        public static string currLang;


        public async Task<bool> LoadDataAsync()
        {
            GetCurrLang();
            Today = new MovieGroup();
            ComingSoon = new MovieGroup();
            Movies = await getMoviesAsync();
            int counter1 = 0;
            int counter2 = 0;
            foreach (MovieData Movie in Movies)
            {

                if (!(Movie.DetailsUrl == null))
                {
                    if (Movie.Today)
                    {
                        Movie.ID = counter1;
                        Today.Items.Add(Movie);
                        counter1++;
                    }
                    else
                    {
                        Movie.ID = counter2;
                        ComingSoon.Items.Add(Movie);
                        counter2++;
                    }
                }
            }

            IsDataLoaded = true;
            return true;
        }

        #region private async Task<MovieGroup> getMoviesAsync()
        private async Task<MovieGroup> getMoviesAsync()
        {
            Uri TodayUri = new Uri("http://www.28cinema.az/" + currLang);
            Uri SoonUri = new Uri("http://www.28cinema.az/" + currLang + "soon/");
            HttpClient client = new HttpClient();
            HtmlDocument htmlDocument = new HtmlDocument();
            HtmlNode htmlNode = new HtmlNode(0, htmlDocument, 1);
            MovieGroup data = new MovieGroup();
            string TodayHtml;
            string SoonHtml;
            try
            {
                TodayHtml = await client.GetStringAsync(TodayUri);
                SoonHtml = await client.GetStringAsync(SoonUri);
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                IsServerReachable = false;
                Console.Out.WriteLine(ex.Message);
                TodayHtml = "";
                return null;
            }
            htmlDocument.LoadHtml(TodayHtml);

            htmlNode = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='poster_wrapper']");
            int i = 0;
            foreach (HtmlNode childNode in htmlNode.ChildNodes)
            {
                string check = GetAttrFromNode(childNode.SelectSingleNode("img"), "title");
                if (check != null)
                {
                    data.Items.Add(new MovieData
                    {
                        ID = i,
                        DetailsUrl = GetAttrFromNode(childNode.SelectSingleNode("div[1]/div[1]/a[1]"), "href"),
                        Title = GetAttrFromNode(childNode.SelectSingleNode("img"), "title"),
                        Poster = GetAttrFromNode(childNode.SelectSingleNode("img"), "src"),
                        IsDetailsLoaded = "Collapsed",
                        Cinema = "28 Cinema",
                        Today = true
                    });
                    i++;
                }
            }

            htmlDocument.LoadHtml(SoonHtml);
            htmlNode = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='poster_wrapper']");
            foreach (HtmlNode childNode in htmlNode.ChildNodes)
            {
                string check = GetAttrFromNode(childNode.SelectSingleNode("a"), "title");
                if (check != null)
                {
                    data.Items.Add(new MovieData
                    {
                        ID = i,
                        DetailsUrl = GetAttrFromNode(childNode.SelectSingleNode("a"), "href"),
                        Title = GetAttrFromNode(childNode.SelectSingleNode("a"), "title"),
                        Poster = GetAttrFromNode(childNode.SelectSingleNode("a/img"), "src"),
                        IsDetailsLoaded = "Collapsed",
                        Cinema = "28 Cinema",
                        Today = false
                    });
                    i++;
                }
            }
            return data;

        }
        #endregion

        #region public static void GetCurrLang()
        public static void GetCurrLang()
        {
            string CurrSystemLang = Thread.CurrentThread.CurrentCulture.Name.Substring(0, 2);
            switch (Settings.DisplayLanguage)
            {
                case "0":
                    if (CurrSystemLang == "az")
                    { currLang = ""; }
                    else
                    {
                        if (CurrSystemLang == "ru")
                        { currLang = "ru/"; }
                        else
                        {
                            currLang = "eng/";
                        }
                    }

                    break;
                case "1":
                    currLang = "eng/";
                    break;
                case "2":
                    currLang = "ru/";
                    break;
                case "3":
                    currLang = "";
                    break;
            }
        }
        #endregion

        #region private string GetAttrFromNode(HtmlNode p, string attr)
        private string GetAttrFromNode(HtmlNode p, string attr)
        {
            if (!(p == null))
            {
                return p.GetAttributeValue(attr, "");
            }
            else
            {
                return null;
            };
        }
        #endregion

        #region //Save data to IS
        public async Task SaveData()
        {

            var data = JsonConvert.SerializeObject(Today);
            IsolatedStorageSettings.ApplicationSettings["Today"] = data;
            data = JsonConvert.SerializeObject(ComingSoon);
            IsolatedStorageSettings.ApplicationSettings["ComingSoon"] = data;
            IsolatedStorageSettings.ApplicationSettings.Save();
        }
        #endregion

        #region //Load data from IS
        public void LoadData()
        {
            string dataFromAppSettings;

            if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("Today", out dataFromAppSettings))
            {
                Today = JsonConvert.DeserializeObject<MovieGroup>(dataFromAppSettings);
            }
            if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("ComingSoon", out dataFromAppSettings))
            {
                ComingSoon = JsonConvert.DeserializeObject<MovieGroup>(dataFromAppSettings);
            }

        }
        #endregion
    }
}
